﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Domain.IRepository.MiniSite;
using YunSpace.Repository.MiniSite;
using YunSpace.ThirdService;

namespace YunSpace.Application.WeChat
{
    public class SmsInfoApp
    {
        private ISmsInfoRepository service = new SmsInfoRepository();


        /// <summary>
        /// 生成短信验证码
        /// </summary>
        public bool ValidCode(string phone)
        {

            var smsMgr = new RongLianSmsManger();
            var code = smsMgr.RandomValidCode();

            var data = smsMgr.SendWeChatInfo(phone, new[] { code });

            var result = !data.Contains("失败");
            if (result)
            {
                var smsinfoEntity = new SmsInfoEntity()
                {
                    F_Phone = phone,
                    F_ValidCode = code,
                    F_Result = data,
                    F_Type = 1
                };
                smsinfoEntity.Create();

                service.Insert(smsinfoEntity);
            }

            return result;
        }

        /// <summary>
        /// 短信验证码是否过期
        /// </summary>
        public bool IsExpire(SmsInfoEntity smsInfoEntity)
        {
            var currentDate = DateTime.Now.AddMinutes(-10);
            var result = service.FindEntity(p =>
                p.F_Phone == smsInfoEntity.F_Phone && p.F_ValidCode == smsInfoEntity.F_ValidCode &&
                p.F_CreatorTime >= currentDate);

            return result == null;

        }
    }
}